<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { onMounted, ref, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '../../stores/token'
import { ElMessage,ElMessageBox, } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { useUserInfoStore } from '../../stores/userInfo'

import { getAssignmentListByCourseIdService } from '../../api/assignment'
import {  getByIdService } from '../../api/course'

import { getScByStudentIdService } from '../../api/sc'
import { addAssignmentService } from '../../api/assSubmit'
const router = useRouter()
const userInfoStore = useUserInfoStore()
let data = userInfoStore.userInfo
const userInfo = ref({
  ...data,
})

const courses = ref([])
const assignments = ref([])

//用户搜索时选中的分类id
const courseId = ref('')

//用户搜索时选中的发布状态
const state = ref('')
const uploadRef = ref(null);
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const assignmentModel = ref({
  id: '',
  title: '',
  courseId: '',
  content: '',
  state: '',
  info: '',
  file:'',
  
})

// 修改是弹窗展示编辑原信息
const showSumbit = (id) => {
  //assignmentModel.value = { ...row }
  // 跳转到前往页面或弹窗逻辑
  router.push({ path: '/student/hw', query: { assId: id } }); 
}

// 显示课程分类和作业
const getCourse = async () => {
    let courseIdResponse = await getScByStudentIdService(userInfo.value.id);
    const courseIdsData = courseIdResponse.data; // 假设返回的数据是课程ID数组  // 提取课程ID
  const courseIds = courseIdsData.map(item => item.couId);  
    const coursesData = []; // 用于存放课程数据
    const assignmentData = []; // 用于存放作业数据

    for (const couId of courseIds) {
      const courseResponse = await getByIdService(couId);
      const assignments = await getAssignmentListByCourseIdService(couId); // 获取作业信息
      coursesData.push({ ...courseResponse.data}); // 组合课程数据和作业
      if(assignments.data.length > 0){
          assignments.data.forEach(assignment => {
          assignment.courseName = courseResponse.data.name;
      });

        assignmentData.push(...assignments.data);
      }
    }
    courses.value = coursesData;
    assignments.value = assignmentData;
}

// 搜索作业
const getAssignment = async () => {
  let filteredAssignments = assignments.value;
  // 根据课程ID过滤
  if (courseId.value) {
    filteredAssignments = filteredAssignments.filter(assignment => assignment.courseId === courseId.value);
  }

  // 根据状态过滤
  if (state.value) {
    filteredAssignments = filteredAssignments.filter(assignment => assignment.overdue === Number(state.value));
  }

  assignments.value = filteredAssignments;
}

//上传作业
const submitAssignment = async () => { 
  assignmentModel.value.stuId =userInfoStore.userInfo.id
  assignmentModel.value.assId = assignmentModel.value.id
  let res = await addAssignmentService(assignmentModel.value)
  visibleDrawer.value = false
  if (res) {
    ElMessage.success(res.message ? res.message : '添加成功')
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，添加失败了')
  }
}
const evaluate = async(id) => {
    // 跳转到前往页面或弹窗逻辑
  router.push({ path: '/assCorrect', query: { assId: id, stuId: userInfo.value.id } }); //携带id查询
}

// 重设下拉框分类信息
const resetCourse = () => {
  courseId.value = ''
  state.value = ''
  getCourse() // 重置时也重新获取作业
}

//清空表单
const clearForm = () => {
  visibleDrawer.value = false
  ElMessage({message:'已取消'})
  if (uploadRef.value) {
    uploadRef.value.clearFiles(); // 清空文件列表
  } else {
    console.error('Upload ref is not available');
  }
}
const overdue = () => {
  ElMessage.error('已超时,请联系老师前往')
}
// 作业时间信息格式化
const formatDate = (row, column) => {
  // 获取单元格数据
  let data = row[column.property]
  if (data == null) {
    return null
  }
  let dt = new Date(data)
  //   return new Intl.DateTimeFormat()
  return (
    dt.getFullYear() +
    '-' +
    (dt.getMonth() + 1) +
    '-' +
    dt.getDate() +
    ' ' +
    dt.getHours() +
    ':' +
    dt.getMinutes()
  )
}
const tableRef = ref(null);  
const isExpand =(row) =>{
  const table = tableRef.value;  // 获取表格的引用
    if (table) {
      table.toggleRowExpansion(row); // 切换展开状态
    }
}
// 刷新时加载
onMounted(() => {
  getCourse()
  getAssignment()
})
</script>
<template>
  
  <el-card class="page-container">
    <!-- 卡牌标题 -->
    <template #header>
      <div class="header">
        <span>您的作业</span>
      </div> 
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="课程分类：">
        <el-select placeholder="请选择" v-model="courseId">
          <el-option
            v-for="course in courses"
            :key="course.id"
            :label="course.name"
            :value="course.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态：">
        <el-select placeholder="请选择" v-model="state">
          <el-option label="开放" value="0"></el-option>
          <el-option label="已截止" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getAssignment">搜索</el-button>
        <el-button @click="resetCourse()">重置</el-button>
      </el-form-item>
    </el-form> 
    <!-- 作业列表 -->
    <el-table ref="table" :data="assignments" style="width: 100%" @row-click="isExpand">
      <el-table-column type="expand">
        <template #default="{ row }">
          <div>
            <p><strong>课程:</strong> {{ row.courseName }}</p>
            <p>作业要求: {{ row.description }}</p>
            <p><strong>作业前往阶段</strong></p>
                <p>截止时间: {{ row.dueDate }}</p>
                <p><strong>作业互评阶段</strong></p>
                <p>开始时间: {{ row.dueDate }}</p>
                <p>截止时间: {{ row.dueDate }}</p>
                <p class="warning-text">{{ row.reviewNote }}</p>
                <p><strong>成绩公布阶段</strong></p>
                <p>公布时间: {{ row.dueDate }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="作业标题" width="150" prop="title" type="index">
        <template #default="{ row }">
          <h1>{{ row.title }}</h1>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" prop="dueDate" :formatter="formatDate"></el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
            {{ row.overdue === 1 ? '已截止' : '开放' }}
        </template>
     </el-table-column> 
     <el-table-column label="成绩" prop="score" :formatter="formatDate"></el-table-column>
      <template #empty>
        <el-empty description="未更新成绩" />
      </template>
    </el-table>
    </el-card>  
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
